package actions;

/**
 * Struts Action的一些标准： 尽量采用Struts DynaValidatorForm定义Form表单
 * 实现必要的验证(一般来说，采用Validator机制验证非空及输入格式；用编程验证其他业务规则） 防止多重提交 资源化（国际化）错误信息
 */
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import service.UserAccountService;
import utils.MenuPermissionAdapter;
import beans.SysDate;
import domain.UserAccount;

/**
 * 登陆Action.
 * @author spring
 */
/**
 * @author spring
 */
public class LoginAction extends Action {
    /**
     * 用户账号业务对象.
     */
    private UserAccountService accountService = null;

    /**
     * 密码有效期（天），小于等于零的数字表示密码不会过期，否则密码超过指定的天数以后将失效（提醒用户改变密码）
     */
    private int passwordValidDays;

    /**
     * @param mapping action mapping
     * @param form action form
     * @param request http request
     * @param response http response
     * @return action forward
     * @throws Exception any exception
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 从Request 中取出请求参数
        String userid = request.getParameter("userID");
        String password =request.getParameter("password");
        String digitCode =request.getParameter("digitCode");
        String sessionDigitValue = (String) request.getSession().getAttribute(
                "digitCode");
        if (digitCode == null || digitCode.equals("")
                || !digitCode.equals(sessionDigitValue)) {// 没有填写验证码 ,返回输入页面
            ActionMessages errMsgs = new ActionMessages();
            errMsgs.add("digitCode", new ActionMessage("errors.loginfailed"));
            this.saveErrors(request, errMsgs);
            return mapping.getInputForward();
        }

        /** 调用 UserAccountService 处理登陆请求* */
        UserAccount curAccount = accountService.loginIn(userid, password);
        if (null == curAccount) {
            // 没有改账户或密码出错 ,返回输入页面
            ActionMessages errMsgs = new ActionMessages();
            errMsgs.add("userID", new ActionMessage("errors.loginfailed"));
            this.saveErrors(request, errMsgs);
            return mapping.getInputForward();
        }

        /** 登陆成功* */
        /** 将用户账号对象放入Session中* */
        request.getSession().setAttribute("HUAXIA_CURRENT_USER", curAccount);
        /** 将系统时间对象放入Application中* */
        servlet.getServletContext().setAttribute("SYSDATE", new SysDate());
        /** 处理登陆成功后的逻辑* */
        afterSuccessLogin(request, response);
        if ((passwordValidDays > 0)
                && ((curAccount.getPasswordLastChangeDate() == null) || ((curAccount
                        .getPasswordLastChangeDate().getTime() + passwordValidDays
                        * 24L * 60 * 60 * 1000) <= System.currentTimeMillis()))) {// 密码有效期过了，需要提醒用户修改密码.
            request.setAttribute("passwordValidDays", passwordValidDays);
            return mapping.findForward("remindchangepassword");
        }

        /** Forward 到 success 页面 * */
        return mapping.findForward("success");
    }

    /**
     * 登陆成功之后的业务逻辑过程.
     * @param request http request
     * @param response http response
     * @throws Exception any exeption
     */
    protected void afterSuccessLogin(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        /** 初始化 动态权限菜单控制器* */
        initDynaMenu(request);
    }

    /**
     * 初始化动态菜单.
     * @param request http request
     * @throws Exception http respones
     */
    private void initDynaMenu(HttpServletRequest request) throws Exception {
        /** 构造Struts menu权限菜单控制器 * */
        MenuPermissionAdapter adapter = new MenuPermissionAdapter(
                (UserAccount) request.getSession().getAttribute(
                        "HUAXIA_CURRENT_USER"));
        request.getSession().setAttribute("HUAXIA_MEN_ADAPTER", adapter);

    }

    /**
     * @param pAccountService The accountService to set.
     */
    public void setAccountService(UserAccountService pAccountService) {
        this.accountService = pAccountService;
    }

    /**
     * @param pPasswordValidDays the passwordValidDays to set
     */
    public void setPasswordValidDays(int pPasswordValidDays) {
        passwordValidDays = pPasswordValidDays;
    }

}
